class MainActivity : WearableActivity() {
    private lateinit var sensorManager: SensorManager
    private var heartRateSensor: Sensor? = null
    
    // 心率阈值
    private val runningModeThreshold = 150
    private val cyclingModeThreshold = 140
    private val fatBurnModeThreshold = 120
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        // 初始化传感器
        sensorManager = getSystemService(SENSOR_SERVICE) as SensorManager
        heartRateSensor = sensorManager.getDefaultSensor(Sensor.TYPE_HEART_RATE)
        
        // 设置模式选择按钮
        btnRunning.setOnClickListener { setMode("running") }
        btnCycling.setOnClickListener { setMode("cycling") }
        btnFatBurn.setOnClickListener { setMode("fatburn") }
        
        // 在类顶部添加
        private var currentThreshold = 120 // 默认阈值
        
        // 在onCreate中添加
        val prefs = getSharedPreferences("HeartRatePrefs", MODE_PRIVATE)
        currentThreshold = prefs.getInt("threshold", 120)
        
        // 添加保存方法
        private fun saveThreshold(threshold: Int) {
            getSharedPreferences("HeartRatePrefs", MODE_PRIVATE).edit()
                .putInt("threshold", threshold)
                .apply()
        }
        
        // 在onCreate中添加阈值设置
        btnSetThreshold.setOnClickListener {
            val threshold = etThreshold.text.toString().toIntOrNull()
            threshold?.let {
                currentThreshold = it
                Toast.makeText(this, "阈值设置为$it", Toast.LENGTH_SHORT).show()
            }
        }
        
        // 启动后台服务
        val serviceIntent = Intent(this, HeartRateService::class.java)
        startForegroundService(serviceIntent)
        
        // 设置定期工作
        val workRequest = PeriodicWorkRequestBuilder<HeartRateWorker>(
            15, TimeUnit.MINUTES  // 每15分钟检查一次
        ).build()
        
        WorkManager.getInstance(this).enqueueUniquePeriodicWork(
            "heart_rate_work",
            ExistingPeriodicWorkPolicy.KEEP,
            workRequest
        )
    }
    
    private fun setMode(mode: String) {
        when(mode) {
            "running" -> currentThreshold = runningModeThreshold
            "cycling" -> currentThreshold = cyclingModeThreshold
            "fatburn" -> currentThreshold = fatBurnModeThreshold
        }
    }
    
    private val heartRateListener = object : SensorEventListener {
        override fun onSensorChanged(event: SensorEvent) {
            val heartRate = event.values[0].toInt()
            tvHeartRate.text = "当前心率: $heartRate"
            
            if(heartRate > currentThreshold) {
                // 触发震动
                vibrateDevice()
            } else if(heartRate < currentThreshold - 20) {
                // 播放提示音
                playAlertSound()
            }
        }
        
        override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {}
    }
    
    private fun vibrateDevice() {
        val vibrator = getSystemService(VIBRATOR_SERVICE) as Vibrator
        val pattern = longArrayOf(0, 500, 500) // 震动模式
        vibrator.vibrate(VibrationEffect.createWaveform(pattern, 0))
    }
    
    private fun playAlertSound() {
        val soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
        val ringtone = RingtoneManager.getRingtone(applicationContext, soundUri)
        ringtone.play()
    }

    override fun onResume() {
        super.onResume()
        heartRateSensor?.let {
            sensorManager.registerListener(
                heartRateListener,
                it,
                SensorManager.SENSOR_DELAY_NORMAL
            )
        }
    }

    override fun onPause() {
        super.onPause()
        sensorManager.unregisterListener(heartRateListener)
    }
}